<template>
  <u-dialog v-model="display_"
            :title="$t('find.title')"
            type="none">
    <q-tabs v-model="tab" :disable="loading">
      <q-tab name="hot" icon="mdi-fire" :label="$t('find.hot')"/>
      <q-tab name="latest" icon="mdi-history" :label="$t('find.latest')"/>
    </q-tabs>
    <q-tab-panels v-model="tab">
      <q-tab-panel name="hot" class="row q-gutter-md">
        <div v-if="lastRefresh" class="col-xs-12 text-grey text-caption">
          {{ $t('find.lastRefresh', { time: dateToString(lastRefresh) }) }}
        </div>
        <div class="col-xs-12" v-if="!hotList" style="height: 200px"/>
        <div class="col-xs-12 text-center" v-else-if="hotList.length === 0">
          {{ $t('find.nothing') }}
        </div>
        <div class="col-xs-12" v-else>
          <div class="row q-col-gutter-md">
            <div class="col-xs-12"
                 v-for="item in hotList"
                 :key="`${item.source}_${item.type}_${item.id}`">
              <song-card :title="item.title ? item.title : $t('find.loading')"
                         :artist="item.artist ? item.artist : $t('find.loading')"
                         :author="item.author ? item.author : $t('find.loading')"
                         :id="item.id"
                         :diffs="item.difficulty"
                         :cover="item.cover ? item.cover : $t('find.loading')"
                         @click="onClickEvent(item.source, item.type, item.id)">
                <template v-slot:image>
                  <q-badge color="primary">
                    {{ item.id }}
                  </q-badge>
                  <q-badge color="red">
                    {{ item.count }}
                    <q-icon name="mdi-fire"/>
                  </q-badge>
                </template>
              </song-card>
            </div>
          </div>
        </div>
      </q-tab-panel>
      <q-tab-panel name="latest">
        <div v-if="!latestList" style="height: 200px"/>
        <div v-else-if="latestList.length === 0" class="text-center">
          {{ $t('find.nothing') }}
        </div>
        <div v-else>
          <div class="row q-col-gutter-md">
            <div class="col-xs-12"
                 v-for="item in latestList"
                 :key="`${item.source}_${item.type}_${item.id}_${item.time}`">
              <song-card :title="item.title ? item.title : $t('find.loading')"
                         :artist="item.artist ? item.artist : $t('find.loading')"
                         :author="item.author ? item.author : $t('find.loading')"
                         :id="item.id"
                         :diffs="item.difficulty"
                         :cover="item.cover ? item.cover : $t('find.loading')"
                         @click="onClickEvent(item.source, item.type, item.id)">
                <template v-slot:image>
                  <q-badge color="primary">
                    {{ item.id }}
                  </q-badge>
                </template>
              </song-card>
            </div>
          </div>
        </div>
      </q-tab-panel>
    </q-tab-panels>
    <q-inner-loading :showing="loading">
      <q-spinner-grid/>
    </q-inner-loading>
  </u-dialog>
</template>

<script>
  import UDialog from "src/components/public/UDialog";
  import * as statistics from 'src/lib/statisticsUtil.js';
  import * as bestdori from 'src/lib/bestdoriAPI.js';
  import notify from "src/lib/notifyUtil";
  import * as optionUtil from "src/lib/playerOptionUtil";
  import {format} from 'quasar';
  import SongCard from "../../components/player/SongCard";

  const {pad} = format;

  export default {
    name: "Find",
    components: {SongCard, UDialog},
    props: {
      display: Boolean
    },
    data: function () {
      return {
        display_: this.display,
        tab: 'hot',
        loading: false,
        lastRefresh: null,
        hotList: null,
        latestList: null
      };
    },
    watch: {
      display_(n) {
        this.$emit('onDisplayChange', n);
        if(n) {
          if (this.tab === 'hot') this.getHotList();
          else if (this.tab === 'latest') this.getLatestList();
        }
      },
      display(n) {
        this.display_ = n;
      },
      tab(n, v) {
        if (n === 'hot') this.getHotList();
        else if (n === 'latest') this.getLatestList();
      }
    },
    computed: {
      langIndex() {
        let option = optionUtil.readPlayerOptions();
        let lang = option.language;
        if (lang.toLowerCase().includes('en_')) return 1;
        else if (lang.toLowerCase() === 'zh_tw') return 2;
        else if (lang.toLowerCase().includes('zh_')) return 3;
        else if (lang.toLowerCase().includes('ko_')) return 4;
        else return 0;
      }
    },
    model: {
      prop: 'display',
      event: 'onDisplayChange'
    },
    methods: {
      async getHotList() {
        this.loading = true;
        this.lastRefresh = null;
        this.hotList = null;
        try {
          let data = await statistics.hotList();
          if (data && data.status) {
            this.lastRefresh = data.lastRefresh;
            this.hotList = data.list.concat();
            this.loading = false;
            for (let i in this.hotList) {
              if (this.hotList[i].source === 'bestdori') {
                if (this.hotList[i].type === 'community') {
                  let data = await bestdori.getCommunityChart(this.hotList[i].id);
                  this.hotList[i].title = data.title;
                  this.hotList[i].artist = data.artist;
                  this.hotList[i].author = data.author;
                  this.hotList[i].difficulty = data.difficulty;
                  this.hotList[i].cover = data.cover;
                } else if (this.hotList[i].type === 'official') {
                  let data = await bestdori.getOfficialChartInfo(this.hotList[i].id, this.langIndex);
                  this.hotList[i].title = data.title;
                  this.hotList[i].artist = data.artist;
                  this.hotList[i].author = this.$t('play.chartSource.bestdori.type.official.label');
                  this.hotList[i].difficulty = data.difficulty;
                  this.hotList[i].cover = data.cover;
                }
              }
              this.hotList = this.hotList.concat();
            }
          }
        } catch (e) {
          notify(this.$t('public.error'), this.$t(e.message), 'clear');
        }
        this.loading = false;
      },
      async getLatestList() {
        this.loading = true;
        this.latestList = null;
        try {
          let data = await statistics.latestList();
          if (data && data.status) {
            this.latestList = data.list.concat();
            this.loading = false;
            for (let i in this.latestList) {
              if (this.latestList[i].source === 'bestdori') {
                if (this.latestList[i].type === 'community') {
                  let data = await bestdori.getCommunityChart(this.latestList[i].id);
                  this.latestList[i].title = data.title;
                  this.latestList[i].artist = data.artist;
                  this.latestList[i].author = data.author;
                  this.latestList[i].difficulty = data.difficulty;
                  this.latestList[i].cover = data.cover;
                } else if (this.latestList[i].type === 'official') {
                  let data = await bestdori.getOfficialChartInfo(this.latestList[i].id, this.langIndex);
                  this.latestList[i].title = data.title;
                  this.latestList[i].artist = data.artist;
                  this.latestList[i].author = this.$t('play.chartSource.bestdori.type.official.label');
                  this.latestList[i].difficulty = data.difficulty;
                  this.latestList[i].cover = data.cover;
                }
              }
              this.latestList = this.latestList.concat();
            }
          }
        } catch (e) {
          notify(this.$t('public.error'), this.$t(e.message), 'clear');
        }
        this.loading = false;
      },
      getFirstNotNull(arr, preferIndex) {
        if (preferIndex && arr[preferIndex]) return arr[preferIndex];
        for (let i in arr) if (arr[i] != null) return arr[i];
        return arr[0];
      },
      onClickEvent(source, type, id) {
        this.$emit('click', source, type, id);
        this.display_ = false;
      },
      dateToString(date) {
        let d = new Date(date);
        return `${pad(d.getFullYear(), 4)}-${pad(d.getMonth() + 1, 2)}-${pad(d.getDate(), 2)}
        ${pad(d.getHours(), 2)}:${pad(d.getMinutes(), 2)}:${pad(d.getSeconds(), 2)}`
      }
    },
    mounted() {
    }
  }
</script>

<style scoped>

</style>
